/**
*Createed by yellowTT's game
*FileName:     ScreenShotUtil.cs
*Author:       yellowTT
*UnityVersion：5.6.0f3
*Date:         2020年09月25日,Friday, 11时33分05秒
*/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScreenShotUtil :MonoBehaviour
{
    public Texture2D m_texture2d;
    private bool m_toScreenCapture;
    private string m_fileName;
    private Rect m_rect;
    private TextureFormat m_textureFormat;

    private int m_desX = 0;
    private int m_desY = 0;
    
    //全景图录制的部分宽高
    private int m_appendWidth = 0;
    private int m_appendHeight = 0;
    //全景图录制的中间渲染纹理
    private Texture2D m_middleRT = null;
    
    //是否持久化全景图纹理
    private bool m_toSerilize;

    public static ScreenShotUtil Get(GameObject go)
    {
        ScreenShotUtil su = go.GetComponent<ScreenShotUtil>();
        if (su == null)
        {
            su = go.AddComponent<ScreenShotUtil>();
        }
        return su;
    }
    
    public static void Remove(GameObject go)
    {
        if(go == null)
        {
            return;
        }
        ScreenShotUtil su = go.GetComponent<ScreenShotUtil>();
        if (su != null)
        {
            GameObject.Destroy(su);
        }
    }

    public string GetImgPath(string _fileName = "ScreenCapture.png")
    {
        string persistentPath = MainConfigPath.PersistentDataPath() + "../shareImg";
        Debug.Log("persistentPath:" +　persistentPath);
        if (Application.isEditor)
        {
            persistentPath = string.Format("{0}/{1}", Application.dataPath+ "/..", "GameResources/shareImg/");
        }
        else
        {
            persistentPath = string.Format("{0}/{1}", persistentPath, "GameResources/shareImg/");
        }
        
        persistentPath = string.Format("{0}{1}", persistentPath, _fileName);
        // MainUtil.Log("persistentn path:" + persistentPath);

        return persistentPath;
    }

    public void ToScreenCapture(string fileName, Rect rect, TextureFormat textureFormat)
    {
        m_fileName = fileName;
        m_rect = rect;
        m_textureFormat = textureFormat;

        m_toScreenCapture = true;
        
        StartCoroutine("ScreenCapture");
    }

    public void WideAngleShot(string fileName, Rect rect, TextureFormat textureFormat)
    {
        m_fileName = fileName;
        m_rect = rect;
        m_textureFormat = textureFormat;
        
        m_toScreenCapture = true;
        Camera.main.fieldOfView = MainConst.WideAngleShotCamFOV;

        StartCoroutine("ScreenCapture");
    }
    
    public void FullViewShot(string fileName, Rect rect, TextureFormat textureFormat,Texture2D screenShot,int destX,int destY,bool toSerilize = false)
    {
        m_fileName = fileName;
        m_rect = rect;
        m_textureFormat = textureFormat;
    
        //纹理纹素值写入的偏移值
        m_desX = destX;
        m_desY = destY;

        m_toSerilize = toSerilize;
        m_toScreenCapture = true;
        
        Camera.main.fieldOfView = MainConst.FullViewShotCamFOV;
        
        StartCoroutine("FullViewScreenCapture",screenShot);
    }

    /// <summary>
    /// 构建新增rect部分的全景图颜色
    /// </summary>
    /// <param name="screenShot"></param>
    /// <param name="middleRT"></param>
    /// <param name="destX">全景图记录的进度/append子全景图时的X起点</param>
    /// <param name="destY"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    public void FullViewShotAppend(Texture2D screenShot,Texture2D middleRT,int destX,int destY,int width,int height,bool toSerilize = false)
    {
        if (m_fileName == null || m_rect == null || m_textureFormat == null)
        {
            MainUtil.LogError("FullViewShotAppend Failed");
            return;;            
        }
    
        //纹理纹素值写入的偏移值
        m_desX = destX;
        m_desY = destY;

        m_appendWidth = width;
        m_appendHeight = height;
        
        m_toSerilize = toSerilize;

        m_middleRT = middleRT;
        Camera.main.fieldOfView = MainConst.FullViewShotCamFOV;

        StartCoroutine("FullViewScreenCaptureAppend",screenShot);
    }

    private IEnumerator FullViewScreenCaptureAppend(Texture2D screenShot)
    {
        yield return new WaitForEndOfFrame();
        if(m_rect != null && m_fileName != null && m_middleRT != null)
        {
            // m_desX = Mathf.Clamp(m_desX, m_desX, m_middleRT.width);
            // m_desY = Mathf.Clamp(m_desY, m_desY, m_middleRT.height);
            m_appendWidth = Mathf.Clamp(m_appendWidth, m_appendWidth, m_middleRT.height);
            m_appendHeight = Mathf.Clamp(m_appendHeight, m_appendHeight, m_middleRT.height);
            //* 第一种实现：开始录制时，立刻记录下屏幕内容，之后根据相机偏转计算偏差值获得新增的全景图
            // Color[] pix = m_middleRT.GetPixels(m_middleRT.width - m_appendWidth,m_desY,m_appendWidth,m_appendHeight);
            //* 第二种实现:一开始从相机内容左侧开始记录，根据相机偏转计算偏差值获得新增的全景图，结束的时候再将右侧当前相机内容里未录入进全景图的部分录入全景图 

            // MainUtil.Log(string.Format("{0}/{1}/{2}/{3}",m_appendWidth,m_appendHeight,m_middleRT.width,m_middleRT.height));
            Color[] pix = m_middleRT.GetPixels(0,m_desY,m_appendWidth,m_appendHeight);

            // Texture2D temp = new Texture2D(Screen.width, Screen.height);
            // temp.ReadPixels(new Rect(0,0,Screen.width,Screen.height), 0, 0);
            // temp.Apply();
            // pix = temp.GetPixels(0,0,m_appendWidth,m_appendHeight);

            screenShot.SetPixels(m_desX, m_desY,m_appendWidth,m_appendHeight, pix);
            screenShot.Apply();
            // MainUtil.Log(string.Format("Append全景图图: 起点： {0}/{1} ; 大小:{2}/{3}", m_desX,m_desY,m_appendWidth,m_appendHeight));
            if (m_toSerilize)
            {
                byte[] bytes = screenShot.EncodeToPNG();
                System.IO.File.WriteAllBytes(m_fileName, bytes);
                MainUtil.Log(string.Format("截图成功: {0}", m_fileName));
                m_texture2d = screenShot;
            }
        }
    }

    private IEnumerator FullViewScreenCapture(Texture2D screenShot)
    {
        yield return new WaitForEndOfFrame();
        if(m_rect != null && m_fileName != null)
        {
            screenShot.ReadPixels(m_rect, m_desX, m_desY);
            screenShot.Apply();
            if (m_toSerilize)
            {
                // if (screenShot.width <= m_desX)
                // {
                //     byte[] bytes = screenShot.EncodeToPNG();
                //     System.IO.File.WriteAllBytes(m_fileName, bytes);
                //     MainUtil.Log(string.Format("截图成功: {0}", m_fileName));
                //     m_texture2d = screenShot;
                // }
                // else//截断
                // {
                //     Texture2D temp2D = new Texture2D(m_desX,Screen.height);
                //     Color[] pix = m_middleRT.GetPixels(0,0,m_desX,Screen.height);
                //     temp2D.SetPixels(0, 0,m_desX,Screen.height, pix);
                //     temp2D.Apply();
                //     
                //     m_texture2d = screenShot;
                // }
                byte[] bytes = screenShot.EncodeToPNG();
                System.IO.File.WriteAllBytes(m_fileName, bytes);
                MainUtil.Log(string.Format("截图成功: {0}", m_fileName));
                m_texture2d = screenShot;
            }
            /*
            LocalMsgManager.Instance.BroadcastMessage(LocalMsgDefine.ScreenCaptureSuccessed);
        */
        }
        else
        {
            /*
            LocalMsgManager.Instance.BroadcastMessage(LocalMsgDefine.ScreenCaptureFailed);
        */
        }
        m_toScreenCapture = false;
        // Camera.main.fieldOfView = MainConst.MainCamFOV;
    }
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="fileName">截图路径+命名</param>
    /// <param name="rect">图片大小</param>
    /// <param name="textureFormat">纹理格式</param>
    /// <returns></returns>
    private IEnumerator ScreenCapture()
    {
        yield return new WaitForEndOfFrame();
        if(m_rect != null && m_fileName != null)
        {
            Texture2D screenShot = new Texture2D((int)m_rect.width, (int)m_rect.height, m_textureFormat, false);

            screenShot.ReadPixels(m_rect, m_desX, m_desY);
            screenShot.Apply();

            byte[] bytes = screenShot.EncodeToPNG();
            System.IO.File.WriteAllBytes(m_fileName, bytes);
// #if UNITY_EDITOR
            MainUtil.Log(string.Format("截图成功: {0}", m_fileName));
// #endif
            m_texture2d = screenShot;
            /*
            LocalMsgManager.Instance.BroadcastMessage(LocalMsgDefine.ScreenCaptureSuccessed);
        */
        }
        else
        {
            /*
            LocalMsgManager.Instance.BroadcastMessage(LocalMsgDefine.ScreenCaptureFailed);
        */
        }
        m_toScreenCapture = false;
        Camera.main.fieldOfView = MainConst.MainCamFOV;
    }

    public void Clear()
    {
        m_texture2d = null;
    }

    
    //void OnPostRender()
    //{
    //    if (m_toScreenCapture)
    //    {
    //        ScreenCapture();
    //        m_toScreenCapture = false;
    //    }

    //}
}
